#include "EPSGLua/LuaFunctions.h"

#include "EPSGLua/Global.h"
#include "EPSGV/Application.h"
#include <time.h>

sigslot::signal0<> EPSGLua::LuaFunctions::s_signalUpdated;

void EPSGLua::LuaFunctions::initialize()
{
	setHierarchy();
}

void EPSGLua::LuaFunctions::updateView()
{
	//s_signalUpdated.emit();
	EPSGV::Application::updateView();
}

sigslot::signal0<> EPSGLua::LuaFunctions::getSignalUpdated()
{
	return s_signalUpdated;
}

void EPSGLua::LuaFunctions::setHierarchy()
{
	luaL_dostring
	(
		Global::instance()->getLuaState(),
		"														\
		function setHierarchy( t, parent )						\
			for k,v in pairs( t ) do							\
				if( t.root and k ~= 'root' )then				\
					newParent = t.root							\
				else											\
					newParent = parent							\
				end												\
				if( type( v ) == 'table' )then					\
					if( k ~= 'asset' and k ~= 'environ' )then	\
						setHierarchy( v, newParent )			\
					end											\
				elseif( newParent )then							\
					if( type( v ) == 'userdata' )then			\
						newParent:addChild( v )					\
					end											\
				end												\
			end													\
		end														\
		"
	);
}

void EPSGLua::LuaFunctions::wait( int ms )
{
	clock_t t1 = clock();
	clock_t t2 = t1;
	while( t2 - t1 < ms * CLOCKS_PER_SEC / 1000 )
		t2 = clock();
}